# -*- coding: utf-8 -*-
 ##############################################
 ##                                            ##
 ##              Principal module               ##
 ##                                             ##
 ##                                             ##
 ##              from Basiq Series              ##
 ##           by Críptidos Digitales            ##
 ##                 GPL (c)2008                 ##
  ##                                            ##
    ##############################################

"""
"""

import os
import time
from PyQt4 import QtCore, QtGui

from cdWidgets import passWidget
from cdWidgets.cdMainWindow import CDMainWindow

from baseModel import *

import principal_ui
import access

import herramientas
import tips
import about



class Form(CDMainWindow):

    @property
    def status(self):
        return self.__status

    def __init__(self, *args, **kwds):

        CDMainWindow.__init__(self, *args)

        self.ui = principal_ui.Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowIcon(QtGui.QIcon("imagenes/logo.png"))
        self.setWindowTitle(app.info['title'])


        self.__status = [0,0]

        self.slide = passWidget.CDPassWidget(self.ui.baseFrame)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        self.slide.setSizePolicy(sizePolicy)
        self.slide.setMode('toggle')

        self.ui.layout.addWidget(self.slide)

        font = QtGui.QFont()
        font.setFamily("Microsoft Sans Serif")
        font.setPointSize(9*app.fontZoom)
        font.setWeight(75)
        font.setBold(True)


        ## MENU SPLITTER
        self.ui.menuSplitter.setHandleWidth(10)
        self.ui.menuSplitter.handle(1).setToolTip('Doble click para ocultar el menu')
        self.connect(self.ui.menuSplitter, QtCore.SIGNAL('handleDoubleClick()'), self.toggleMenu)


        ## HERRAMIENTAS
        self.ui.herramientas = herramientas.Forma(self.ui.baseFrame, owner=self)
        self.slide.addWidget(self.ui.herramientas)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("imagenes/Tools.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.toolsAC = QtGui.QAction(icon, u"&Herramientas", self)
        self.toolsAC.setCheckable(False)
        self.toolsAC.setIconText(u"&Herramientas")

        self.ui.toolsTO.setDefaultAction(self.toolsAC)

        self.connect(self.toolsAC, QtCore.SIGNAL("triggered()"), self.showHerramientas)


        self.connect(self, QtCore.SIGNAL('priceRulesChanged()'), self.priceRulesChanged)

        ## PRINCIPAL
        lb1 = QtGui.QLabel(self.slide)
        lb1.setPixmap(QtGui.QPixmap("imagenes/logo.png"))

        frame0 = QtGui.QFrame(self.ui.baseFrame)
        frame0.setStyleSheet("background-color:#B0B070;")

        self.ui.layout0 = QtGui.QHBoxLayout(frame0)
        self.ui.layout0.addItem(QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum))
        self.ui.layout0.addWidget(lb1)
        self.ui.layout0.addItem(QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum))

        self.slide.addWidget(frame0, 0, True)

        ## INFORMACIÓN
        self.ui.informacion = QtGui.QTextEdit(self)
        self.ui.informacion.hide()
        self.ui.informacion.setStyleSheet("background-color:#FFFFA0;")
        self.informacion = u"Empresa Básica, the best!"

        self.connect(self.ui.toInformacion, QtCore.SIGNAL('enter()'), self.showInformacion)
        self.connect(self.ui.toInformacion, QtCore.SIGNAL('leave()'), self.hideInformacion)
        self.connect(self.ui.toInformacion, QtCore.SIGNAL('clicked()'), self.about)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("imagenes/Shotdown.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.exitAC = QtGui.QAction(icon, u"&Salir", self)
        self.exitAC.setCheckable(False)
        self.exitAC.setIconText(u"&Salir")
        self.connect(self.exitAC, QtCore.SIGNAL("triggered()"), self.salir)

        self.ui.exitTO.setDefaultAction(self.exitAC)

        ## TIPS
        self.ui.tips = tips.Forma()
        if getAttribute(grupo=u'sistema', nombre=u'mostrarTips')['valor'] == u"1":
            self.ui.tips.show()
        #~ self.connect(self.ui.tips, QtCore.SIGNAL('mostrarTipsChanged()'), self.mostrarTipsChanged)

        if session.config.pull('layout', 'windowState'):
            self.restoreGeometry(QtCore.QByteArray().fromBase64(session.config.pull('layout', 'windowState')))
        else:
            geometry = app.screenGeometry
            self.setGeometry(geometry.width()*.15, geometry.height()*.15, geometry.width()*.70, geometry.height()*.70)
            self.setWindowState(self.windowState() ^ QtCore.Qt.WindowMaximized)

        # self.ui.sectionsFR.setMaximumWidth(self.ui.buttonsFR.width())

        self.connect(self, QtCore.SIGNAL('F10Pressed()'), self.focusMainTools)
        self.connect(self, QtCore.SIGNAL('proteccionF10Changed()'), self.proteccionF10Changed)

        self.ui.currentLA.setOrientation(u'up')
        self.ui.currentLA.setMaximumWidth(50)


    def toggleMenu(self):
        print "principal.toggleMenu()"
        if self.ui.menuSplitter.sizes()[1]:
            self.ui.menuSplitter.setSizes([1, 0])
        else:
            self.ui.menuSplitter.setSizes([1, 1])


    def about(self):
        form = about.Form(self, owner=self)
        # form.exec_()
        result = form.show()


    def closeEvent(self, event):
        self.ui.tips.destroy()
        session.config.push('layout', 'windowstate', self.saveGeometry().toBase64())
        #~ close()

    def focusMainTools(self):
        if getAttribute(grupo=u'sistema', nombre=u'proteccionF10')['valor']:
            if self.ui.frameBotones.isEnabled():
                self.ui.frameBotones.setEnabled(False)
                self.ui.frameBotones.setToolTip(u"Presiona F10 para activar esta barra")
            else:
                self.ui.frameBotones.setEnabled(True)
                self.ui.frameBotones.setToolTip("")
                self.ui.frameBotones.setFocus()

    def hideInformacion(self):
        self.ui.informacion.hide()

    def priceRulesChanged(self):
        loadPriceRules()
        self.emit(QtCore.SIGNAL('priceRulesChangedBroadcast()'))

    def proteccionF10Changed(self):
        if getAttribute(grupo=u'sistema', nombre=u'proteccionF10')['valor']:
            self.ui.frameBotones.setEnabled(False)
            self.ui.frameBotones.setToolTip(u"Presiona F10 para activar esta barra")


    def salir(self):
        self.close()

    def showAdministracion(self):
        self.ui.currentLA.setText(u'CONTROL DE PROCESOS')
        self.ui.currentLA.setStyleSheet("QLabel {color:#00C000; background-color:qlineargradient(x1:0,y1:0,X2:1,y2:1,stop:0 #80FF80, stop:.5 #FFFFFF stop:1 #80FF80); border-radius:9; border-color:#808080; border-width:1; border-style:outset; padding:3;}")

        if self.slide.currentWidget() != self.ui.administracion:
            self.slide.show(self.ui.administracion)
            self.__status[0] = u'management'
        else:
            app.beep()

        if getAttribute(grupo=u'sistema', nombre=u'proteccionF10')['valor']:
            self.ui.frameBotones.setEnabled(False)
            self.ui.frameBotones.setToolTip(u"Presiona F10 para activar esta barra")

    def showHerramientas(self):
        if not self.slide.currentWidget() == self.ui.herramientas:
            if getAttribute(grupo=u'sistema', nombre=u'contrasenaHerramientas')['referencia']:
                formaAcceso = access.Form(u"Acceso a Herramientas", modo=u'herramientas')
                result = formaAcceso.exec_()
                formaAcceso.destroy()
            else:
                result = QtGui.QDialog.Accepted
            if result == QtGui.QDialog.Accepted:
                self.slide.show(self.ui.herramientas)
                self.informacion = u"Mucho cuidado con lo que haces en este módulo"
                self.__status[0] = u'tools'
        else:
            app.beep()

    def showInformacion(self):
        # print 'principal.showInformacion()'

        if self.informacion:
            self.ui.informacion.setGeometry(self.ui.toInformacion.x()+40, self.height()-250, 250, 180)
            self.ui.informacion.setText(self.informacion)
            self.ui.informacion.show()
            self.__status[0] = u'information'

    def showMantenimiento(self):
        self.ui.currentLA.setText(u'CONTROL DE PROCESOS')
        self.ui.currentLA.setStyleSheet("QLabel {color:#00C000; background-color:qlineargradient(x1:0,y1:0,X2:1,y2:1,stop:0 #80FF80, stop:.5 #FFFFFF stop:1 #80FF80); border-radius:9; border-color:#808080; border-width:1; border-style:outset; padding:3;}")
        if not self.slide.currentWidget() == self.ui.mantenimiento:
            if getAttribute(grupo=u'sistema', nombre=u'contrasenaMantenimiento')['referencia']:
                formaAcceso = access.Form(u"Acceso a Mantenimiento", modo=u'herramientas')
                result = formaAcceso.exec_()
                formaAcceso.destroy()
            else:
                result = QtGui.QDialog.Accepted
            if result:
                self.slide.show(self.ui.mantenimiento)
                self.__status[0] = u'maintenance'
                if getAttribute(grupo=u'sistema', nombre=u'proteccionF10')['valor']:
                    self.ui.frameBotones.setEnabled(False)
                    self.ui.frameBotones.setToolTip(u"Presiona F10 para activar esta barra")
        else:
            app.beep()
            if getAttribute(grupo=u'sistema', nombre=u'proteccionF10')['valor']:
                self.ui.frameBotones.setEnabled(False)
                self.ui.frameBotones.setToolTip(u"Presiona F10 para activar esta barra")

    def showPuntoVenta(self):
        self.ui.currentLA.setText(u'PUNTO DE VENTA')
        self.ui.currentLA.setStyleSheet("QLabel {color:#0000FF; background-color:qlineargradient(x1:0,y1:0,X2:1,y2:1,stop:0 #70A0F0, stop:.5 #FFFFFF stop:1 #70A0F0); padding:3;}")
        if self.slide.currentWidget() != self.ui.puntoVenta:
            self.slide.show(self.ui.puntoVenta)
            self.__status[0] = u'pos'
        else:
            app.beep()

        if getAttribute(grupo=u'sistema', nombre=u'proteccionF10')['valor']:
            self.ui.frameBotones.setEnabled(False)
            self.ui.frameBotones.setToolTip(u"Presiona F10 para activar esta barra")




